<?php
    require('./Utils.php');

    $post = getJsonParamter();

    $username = $post['username'];
    $order_number = $post['order_number'];


    $conn = getConnection();

    mysqli_autocommit($conn, FALSE);
    
    $sql = "SELECT o.id, status, SUM(price * pet_number) price
            FROM `order` o LEFT JOIN pet_order po 
            ON o.id = po.order_id
            LEFT JOIN pet p
            ON po.pet_id = p.id
            WHERE user_id = ? AND o.id = ?";

    $res = query($conn, $sql, $username, $order_number);
    $price = $res['price'];#获取订单价格
    $status = $res['status'];

    $sql = "SELECT amount FROM user
            WHERE username = ?";

    $res = query($conn, $sql, $username);
    $amount = $res['amount']; #获取用户余额

    if($amount < $price){
        getJson(500,'余额不足', null);
        return;
    }


    else if($status || $status == null){
        getJson(500, '提交订单异常, 订单不存在或订单已支付', null);
        return;
    }

    $sql = "UPDATE user SET amount = amount - ? WHERE username = ?";
    $result1 = execute($conn, $sql, $price, $username);


    $sql = "UPDATE `order` SET status = 1 WHERE id = ?";
    $result2 = execute($conn, $sql, $order_number);

    if($result1 && $result2){
        mysqli_commit($conn);
        getJson(200, '提交订单成功', null);
    }

    else{
        getJson(500, '提交订单异常', null);
    }
?>